package demo.tree;

/**
 * 返回二叉树中最大的二叉搜索子树的大小
 */
public class MaxSubBSTSize {
    public static void main(String[] args) {
        Node node = buildTree();
        TreeUtil.treePrint(node);
        System.out.println(getMaxSubBSTSize(node));
    }

    public static int getMaxSubBSTSize(Node head) {
        if (head == null) {
            return 0;
        }
        return process(head).maxSubBSTSize;
    }

    public static Node buildTree() {
        Node node1 = new Node(0);
        Node node2 = new Node(3);
        Node node3 = new Node(4);
        Node node4 = new Node(2);
        Node node5 = new Node(5);
        Node node6 = new Node(7);
        Node node7 = new Node(6);

        node1.left = node2;
        node1.right = node3;
        node2.left = node4;
        node2.right = node5;
        node3.right = node6;
        node5.left = node7;
        return node1;
    }

    private static class Info {
        public boolean isAllBST;
        public int maxSubBSTSize;
        public int min;
        public int max;

        public Info(boolean isAllBST, int maxSubBSTSize, int min, int max) {
            this.isAllBST = isAllBST;
            this.maxSubBSTSize = maxSubBSTSize;
            this.min = min;
            this.max = max;
        }
    }

    public static Info process(Node node) {
        if (node == null) {
            return null;
        }
        Info leftInfo = process(node.left);
        Info rightInfo = process(node.right);
        int min = node.value;
        int max = node.value;
        int maxSubBSTSize = 0;
        if (leftInfo != null) {
            min = Math.min(min, leftInfo.min);
            max = Math.max(max, leftInfo.max);
            maxSubBSTSize = Math.max(maxSubBSTSize, leftInfo.maxSubBSTSize);
        }
        if (rightInfo != null) {
            min = Math.min(min, rightInfo.min);
            max = Math.max(max, rightInfo.max);
            maxSubBSTSize = Math.max(maxSubBSTSize, rightInfo.maxSubBSTSize);
        }

        boolean isBST = false;
        if ((leftInfo == null ? true : (leftInfo.isAllBST && leftInfo.max < node.value))
                && (rightInfo == null ? true : (rightInfo.isAllBST && rightInfo.min > node.value))) {
            isBST = true;
            maxSubBSTSize = (leftInfo == null ? 0 : leftInfo.maxSubBSTSize) + (rightInfo == null ? 0 : rightInfo.maxSubBSTSize) + 1;
        }
        return new Info(isBST, maxSubBSTSize, min, max);
    }
}
